import { WidgetOption, WidgetType } from '@/types'
import input from '../input'
import { usingValidate } from '../input/utils'
import IdSetting from './IdSetting.vue'
import IdFill from './IdFill.vue'

/** 是否身份证号码 */
export function isId(val: string) {
  return val && /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(val)
}

const ERROR_INVALID_ID = '身份证号格式错误，请重新输入'

/** 身份证号码 */
export default {
  ...input,
  key: 'id',
  name: '身份证号',
  type: WidgetType.ID,
  icon: 'fa-icon-widget-id',
  text: {
    maxLength: 18
  },

  settingComponent: IdSetting,
  fillingComponent: IdFill,

  settingValidate(widget) {
    const { value } = widget

    if (value && !isId(value as string)) {
      return ERROR_INVALID_ID
    }
  },

  usingValidate(widget) {
    const error = usingValidate(widget)

    if (error) return error

    const { value } = widget

    if (value && !isId(value as string)) {
      return ERROR_INVALID_ID
    }
  }
} as WidgetOption
